<template>
  <el-card>
    <template #header>
      <div class="flex-x-between">
        <div class="flex-y-center">已决赔款总额</div>
      </div>
    </template>

    <div :id="id" :class="className" :style="{ height, width }" />
  </el-card>
</template>

<script setup lang="ts">
import * as echarts from 'echarts';
import { ref, onMounted, onBeforeUnmount, onActivated, markRaw, watch, Ref, UnwrapRef } from 'vue';
import { Nyt7ClaimVO } from '@/api/Nyt7Claim/Nyt7Claim/types';
import { PostVO } from '@/api/system/post/types';
import { Nyt7RegionManagementVO } from '@/api/Nyt7RegionManagement/Nyt7RegionManagement/types';
import { addNyt7Claim, delNyt7Claim, updateNyt7Claim } from '@/api/Nyt7Claim/Nyt7Claim';

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const Nyt7ClaimFormRef = ref<ElFormInstance>();
const buttonLoading = ref(false);
const selectedData = ref<Nyt7ClaimVO | null>(null);
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const loading = ref(true);
/** 提交按钮 */
const submitForm = () => {
  Nyt7ClaimFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (selectedData.value.id) {
        selectedData.value.createTime = null;
        await updateNyt7Claim(selectedData.value).finally(() => (buttonLoading.value = false));
      } else {
        await addNyt7Claim(selectedData.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      // 调用传递的方法
      await props.refreshChartData();
    }
  });


};

/** 删除按钮操作 */
const handleDelete = async (row?: UnwrapRef<Nyt7ClaimVO['id']>) => {
  await proxy?.$modal.confirm('是否确认删除此条数据项？').finally(() => (loading.value = false));
  await delNyt7Claim(row);
  proxy?.$modal.msgSuccess('删除成功');
  dialog.visible = false;
  // 调用传递的方法
  await props.refreshChartData();

};

// 图表对象
const chart: Ref<echarts.ECharts | null> = ref(null);

const props = defineProps({
  id: {
    type: String,
    default: '已决赔款总额'
  },
  className: {
    type: String,
    default: ''
  },
  width: {
    type: String,
    default: '200px',
    required: true
  },
  height: {
    type: String,
    default: '200px',
    required: true
  },
  chartData: {
    type: Object as () => Nyt7ClaimVO[] | null,
    default: null
  },
  postOptions: {
    type: Array as () => PostVO[],
    default: () => []
  },
  cityOptions: {
    type: Array as () => Nyt7RegionManagementVO[],
    default: () => []
  },
  CategoryOptions: {
    type: Array as () => any,
    default: () => []
  },
  refreshChartData: {
    type: Function as PropType<() => void>,
    required: true
  }
});

// 初始 option
const option = {};

// 窗口大小变化时，重置图表大小
const handleResize = () => {
  setTimeout(() => {
    if (chart.value) {
      chart.value.resize();
    }
  }, 100);
};

/** 取消按钮 */
const cancel = () => {

  dialog.visible = false;
  props.refreshChartData();
};

// 初始化图表
onMounted(() => {
  chart.value = markRaw(echarts.init(document.getElementById(props.id) as HTMLDivElement));

  chart.value.setOption(option);

  window.addEventListener('resize', handleResize);
});

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize);
});

onActivated(() => {
  handleResize();
});

watch(
  () => props.chartData,
  (newData) => {
    if (newData) {
      console.log('newData', newData);
      // 提取 newData 中的对象属性，形成二维数组
      const data = newData.map((item) => [
        item.companyName,
        item.region, // 区域
        item.insuranceType, // 险种
        item.claimAmount, // 已决赔款总额
        item.claimArea, // 已决赔款面积
        item.claimHouseholds, // 已决赔款户数
        item.createTime, // 日期
        item.id
      ]);
      // 对数据进行排序
      data.sort((a, b) => new Date(a[5]).getTime() - new Date(b[5]).getTime());
      console.log('data', data);
      // 生成 option 和 drilldownData
      const groupedData = newData.reduce((acc, item) => {
        if (!acc[item.companyName]) {
          acc[item.companyName] = {
            dataGroupId: item.companyName,
            data: []
          };
        }
        acc[item.companyName].data.push([item.insuranceType, item.claimArea]);
        return acc;
      }, {});
      console.log('groupedData', groupedData);
      const xAxisData = Object.keys(groupedData);
      const seriesData = xAxisData.map((companyName) => ({
        value: groupedData[companyName].data.reduce((sum, item) => sum + item[1], 0),
        groupId: companyName
      }));

      const drilldownData = Object.values(groupedData);

      // 如果 groupedData 只有一条数据，直接显示下钻视图
      if (Object.keys(groupedData).length === 1) {
        const companyName = xAxisData[0];
        const subData = drilldownData.find((data) => data.dataGroupId === companyName);
        if (subData) {
          chart.value.setOption({
            xAxis: {
              data: subData.data.map((item) => item[0]),
              type: 'category',
              axisLabel: { interval: 0, rotate: 20 }
            },
            yAxis: [
              {
                type: 'value'
              }
            ],
            series: {
              type: 'bar',
              id: 'sales',
              dataGroupId: subData.dataGroupId,
              data: subData.data.map((item) => item[1]),
              universalTransition: {
                enabled: true,
                divideShape: 'clone'
              }
            },
            tooltip: {
              trigger: 'item',
              formatter: (params: any) => {
                if (params.componentType === 'series') {
                  const data = newData.find((item) => item.insuranceType === params.name);
                  if (data) {
                    return `保险公司: ${data.companyName}<br/>
                      区域: ${data.region}<br/>
                      险种: ${data.insuranceType}<br/>
                      已决赔款总额: ${data.claimAmount}<br/>
                      已决赔款面积: ${data.claimArea}<br/>
                      已决赔款户数: ${data.claimHouseholds}<br/>
                      创建时间: ${data.createTime}<br/>`;
                  }
                }
                return '';
              }
            }
          });
        }
      } else {
        // 更新 option
        chart.value.setOption({
          xAxis: {
            data: xAxisData,
            type: 'category',
            axisLabel: { interval: 0, rotate: 20 }
          },
          yAxis: [
            {
              type: 'value'
            }
          ],
          dataGroupId: '',
          animationDurationUpdate: 500,
          series: {
            type: 'bar',
            id: 'sales',
            data: seriesData,
            universalTransition: {
              enabled: true,
              divideShape: 'clone'
            }
          }
        });

        // 添加点击事件监听
        chart.value.off('click');
        chart.value.on('click', (params: any) => {
          // 主视图
          const companyName = params.data.groupId;

          // 找到对应的完整数据项
          const fullData = newData.filter(item => item.companyName === companyName);
          if (params.componentType === 'series') {
            if (params.data.groupId) {
              // 主视图点击
              const subData = drilldownData.find((data) => data.dataGroupId === params.data.groupId);
              if (!subData) {
                return;
              }
              chart.value.setOption({
                xAxis: {
                  data: subData.data.map((item) => item[0]),
                  type: 'category',
                  axisLabel: { interval: 0, rotate: 20 }
                },
                yAxis: [
                  {
                    type: 'value'
                  }
                ],
                series: {
                  type: 'bar',
                  id: 'sales',
                  dataGroupId: subData.dataGroupId,
                  data: subData.data.map((item) => item[1]),
                  universalTransition: {
                    enabled: true,
                    divideShape: 'clone'
                  }
                },
                graphic: [
                  {
                    type: 'group',
                    left: 10,
                    top: 5,
                    children: [
                      {
                        type: 'rect',
                        shape: {
                          width: 70,
                          height: 30,
                          r: 5 // 圆角
                        },
                        style: {
                          fill: '#1E90FF', // 背景颜色
                          stroke: '#1E90FF', // 边框颜色
                          lineWidth: 1
                        }
                      },
                      {
                        type: 'text',
                        style: {
                          text: '返回',
                          fontSize: 16,
                          fill: '#fff', // 文字颜色
                          x: 35,
                          y: 9,
                          textAlign: 'center'
                        }
                      }
                    ],
                    onclick: () => {
                      chart.value.setOption({
                        xAxis: {
                          data: xAxisData,
                          type: 'category',
                          axisLabel: { interval: 0, rotate: 20 }
                        },
                        yAxis: [
                          {
                            type: 'value'
                          }
                        ],
                        series: {
                          type: 'bar',
                          id: 'sales',
                          data: seriesData,
                          universalTransition: {
                            enabled: true,
                            divideShape: 'clone'
                          }
                        },
                        graphic: [
                          {
                            children: [
                              {
                                type: '',
                                shape: {
                                  width: 0,
                                  height: 0,
                                  r: 5 // 圆角
                                },
                                style: {
                                  fill: '', // 背景颜色
                                  stroke: '', // 边框颜色
                                  lineWidth: 1
                                }
                              },
                              {
                                type: '',
                                style: {
                                  text: '',
                                  fontSize: 0,
                                  fill: '', // 文字颜色
                                  x: 0,
                                  y: 0,
                                  textAlign: 'center'
                                }
                              }
                            ]
                          }
                        ]
                      });
                    }
                  }
                ],
                tooltip: {
                  trigger: 'item',
                  formatter: (params: any) => {
                    if (params.componentType === 'series') {
                      const data = fullData.find((item) => item.insuranceType === params.name);
                      if (data) {
                        return `保险公司: ${data.companyName}<br/>
                          区域: ${data.region}<br/>
                          险种: ${data.insuranceType}<br/>
                          已决赔款总额: ${data.claimAmount}<br/>
                          已决赔款面积: ${data.claimArea}<br/>
                          已决赔款户数: ${data.claimHouseholds}<br/>
                          创建时间: ${data.createTime}<br/>`;
                      }
                    }
                    return '';
                  }
                }
              });
            }
          }
        });
      }
    }
  },
  { immediate: true }
);

</script>

<style lang="scss" scoped></style>
